package com.h3bpm.kumhosunny.purchase.controller;

import OThinker.Common.DateTimeUtil;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.kumhosunny.common.H3Property;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhengyj
 * @date 2019/8/12
 * @description 验收标准控制器
 */
@Controller
@RequestMapping("/Portal/kumhosunny/acceptanceStandardApp")
public class AcceptanceStandardAppController extends ControllerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);

    /**
     * 到货验收 子表
     */
    private final static String INSPECTIONINCOMINGMERCHANDISE = "inspectionIncomingMerchandise";
    /**
     * 使用验收 子表
     */
    private final static String USINGACCEPTANCE = "usingAcceptance";

    /**
     * 验收标准
     */
    private final static String CHECKSTANDARD = "checkStandard";
    /**
     * 验收制定人
     */
    private final static String NOMINATOR = "nominator";
    /**
     * 验收子流程
     */
    private final static String NOTICEACCEPTANCE = "noticeAcceptance";

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String getFunctionCode() {
        return null;
    }


    /****
     * 功能描述: 验收标准流程完结后 根据 到货验收子表 和 使用验收子表  来 创建 验收标准子流程 即 验收通知单
     *
     * @Param: [instanceId]
     * @Return: void
     * @Author: zhengyj
     * @Date: 2019/8/15 11:32
     */
    @RequestMapping(value = "/createNoticeAcceptance", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void createNoticeAcceptance(String instanceId) {
        LOGGER.warn("=======创建验收标准子流程==========Start========instanceId:" + instanceId);

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
            String projectName = (String) valueTable.get("projectName");
            String projectNember = (String) valueTable.get("projectNumber");
            // 根据 到货验收子表 发起子流程
            createNoticeAcceptanceByDeatil(INSPECTIONINCOMINGMERCHANDISE, valueTable, instanceId,projectName,projectNember);
            // 根据 使用验收子表 发起子流程
            createNoticeAcceptanceByDeatil(USINGACCEPTANCE, valueTable, instanceId,projectName,projectNember);

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

    /****
     * 功能描述: 根据子表名 来 发起 验收标准子流程
     *
     * @Param: [detailTableName, valueTable, instanceId]
     * @Return: void
     * @Author: zhengyj
     * @Date: 2019/8/15 11:33
     */
    private void createNoticeAcceptanceByDeatil(String detailTableName, HashMap<String, Object> valueTable, String instanceId,String projectName,String projectNember) throws Exception {
        LOGGER.warn("=======创建验收标准子流程=============instanceId:" + instanceId);
        BizObject[] detailTable = (BizObject[]) valueTable.get(detailTableName);
       String projectNumber = (String) valueTable.get("projectNumber");
        if (null != detailTable) {
            for (BizObject detail : detailTable) {
                List<DataItemParam> paramValues = new ArrayList<>();
                HashMap<String, Object> detailValueTable = detail.getValueTable();

                User nominator = (User) getEngine().getOrganization().GetUnit(detailValueTable.get(NOMINATOR).toString());

                if (!nominator.getName().isEmpty()) {

                    paramValues.add(new DataItemParam("soureInstanceId", instanceId));

                    paramValues.add(new DataItemParam("soureTableName", detailTableName));

                    paramValues.add(new DataItemParam("soureObjectId", detailValueTable.get(H3Property.OBJECTID)));

                    paramValues.add(new DataItemParam("projectName", projectName));

                    paramValues.add(new DataItemParam("projectNumber",projectNumber));
                    if(detailTableName.equals(USINGACCEPTANCE)){
                        paramValues.add(new DataItemParam("ysType","使用验收"));
                    }else{
                        paramValues.add(new DataItemParam("ysType","到货验收"));
                    }

                    paramValues.add(new DataItemParam("acceptanceStandard", detailValueTable.get(CHECKSTANDARD)));

                    paramValues.add(new DataItemParam("acceptanceDesigner", nominator.getName()));

                    paramValues.add(new DataItemParam("projectLeader", valueTable.get(H3Property.CREATEDBY)));
                    LOGGER.info("======根据 " + detailTableName + " 发起子流程=========发起人:" + nominator.getName());
                    BPMServiceResult bpmServiceResult = bpmService.StartWorkflow(H3Property.SYSTEMCODE, H3Property.SECRET, NOTICEACCEPTANCE, nominator.getCode(), false, paramValues);
                    LOGGER.info(">> " + objectMapper.writeValueAsString(bpmServiceResult));
                }
            }
        }
    }


    /****
     * 功能描述: 获取项目编号 每月更新。取 年月 + 三位递增数
     *
     * @Param: []
     * @Return: com.h3bpm.base.res.ResBody
     * @Author: zhengyj
     * @Date: 2019/9/20 13:56
     */
    @RequestMapping(value = "/getSystemProjectNumber", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResBody getSystemProjectNumber() {
        LOGGER.warn("==========获取项目编号 每月更新===========");
        String returnProjectNumber = "";
        Date date = new Date();
        String dateStr = DateTimeUtil.getYear(date) + "" + String.format("%02d", DateTimeUtil.getMonth(date));
        String querySql = " SELECT projectNumber from I_projectInit WHERE projectNumber LIKE '" + dateStr + "%' ORDER BY projectNumber DESC LIMIT 1 ";

        try {
            DataTable dataTable = SqlUtil.doQuery(querySql);

            if (dataTable.getRows() != null && dataTable.getRows().size() > 0) {
                String projectNumber = dataTable.getRows().get(0).getString(0);
                int num = Integer.valueOf(projectNumber.split(dateStr)[1]);
                returnProjectNumber = dateStr + String.format("%03d", num + 1);
            } else {
                returnProjectNumber = dateStr + "001";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        LOGGER.info("=======生成的项目编号======" + returnProjectNumber);
        return ResBody.buildSuccessResBody(returnProjectNumber);
    }


}
